package cn.superchart.web.core.config;

import cn.superchart.common.base.BaseUserDetails;
import cn.superchart.common.properties.SecurityProperties;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.CacheManager;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.template.QuickConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.time.Duration;
import java.util.List;

@Configuration
public class CacheConfig {


    private final CacheManager cacheManager;

    private final SecurityProperties securityProperties;

    public CacheConfig(CacheManager cacheManager, SecurityProperties securityProperties) {
        this.cacheManager = cacheManager;
        this.securityProperties = securityProperties;
    }


    @Bean("userCache")
    public Cache<String, BaseUserDetails> userCache() {
        String cacheType = securityProperties.getJwt().getCacheType().toLowerCase();
        QuickConfig.Builder build = QuickConfig.newBuilder("userCache")
        .expire(Duration.ofSeconds(securityProperties.getJwt().getExpire()))
        .localLimit(500000)
        .syncLocal(true);
        if("local".equals(cacheType)){
            build.cacheType(CacheType.LOCAL);
        }else if("redis".equals(cacheType)){
            build.cacheType(CacheType.REMOTE);
        }
        QuickConfig qc =  build.build();
        return cacheManager.getOrCreateCache(qc);
    }


    @Bean("authCache")
    public Cache<String, List<SimpleGrantedAuthority>> authCache() {
        String cacheType = securityProperties.getJwt().getCacheType().toLowerCase();
        QuickConfig.Builder build = QuickConfig.newBuilder("authCache")
        .expire(Duration.ofSeconds(securityProperties.getJwt().getExpire()))
        .localLimit(500000)
        .syncLocal(true);
        if("local".equals(cacheType)){
            build.cacheType(CacheType.LOCAL);
        }else if("redis".equals(cacheType)){
            build.cacheType(CacheType.REMOTE);
        }
        QuickConfig qc =  build.build();
        return cacheManager.getOrCreateCache(qc);
    }

}
